<!-- p_purchase.ftl 采购单 -->
var PPurchase = {
    u: '/pPurchase',
    uList: '/pPurchase/list',
    uEdit: '/pPurchase/doEdit',
    editIndex: -1,
    supplierArr: [],
    unitArr: [],
    canSave: true,
    isDg: 0,
    winThat:undefined,
    dgType:undefined,
    repositoryArr:[],
};

$.extend($.fn.datagrid.defaults.editors, {
    house: {
        init: function (container, options) {
            return $('<div style="text-align: center">编辑</div>').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            var rows = PPurchase.dtable.datagrid("getRows");
            var house = rows[PPurchase.editIndex].house;
            return house;
        },
        setValue: function (target, value) {
        },
        resize: function (target, width) {
            $(target).click(function () {
                PPurchase.isDg = 1;
                var rows = PPurchase.dtable.datagrid("getRows");
                var skuId = rows[PPurchase.editIndex].skusId;
                var house = rows[PPurchase.editIndex].house;
                var href = "/wWearhouse/treeGrid?skuId=" + skuId + "&house=" + house + "&type=1";//type 0出库 1入库
                var $dg = $yd.win.create('仓库/库位', href);
                $dg.width = "450px;";
                $dg.height = "520px;";
                $dg.open(function (that, $win) {
                    PPurchase.winThat = that;
                    PPurchase.dgType = "house";
                }, function (that, $win) {
                    PPurchase.saveDgHouse();
                }, function () {
                    if (PPurchase.editIndex > -1) {
                        PPurchase.dtable.datagrid('endEdit', PPurchase.editIndex);
                    }
                    PPurchase.editIndex = -1;
                    PPurchase.isDg = 0;
                    PPurchase.winThat = undefined;
                    PPurchase.dgType = undefined;
                });
            });

            $(target)._outerWidth(width);
        }
    }
});
PPurchase.saveDgHouse = function () {
    var data = KW.getResult();
    var wearhouseId = "";
    var positionId = "";
    if (!PPurchase.isEmpty(data)) {
        var arr = data.split("_");
        wearhouseId = arr[0];
        positionId = arr[2];
    }
    PPurchase.dtable.datagrid('updateRow', {
        index: PPurchase.editIndex,
        row: {
            house: data,
            wearhouseId: wearhouseId,
            positionId: positionId
        }
    });

    PPurchase.winThat.close();
    PPurchase.isDg = 0;
    PPurchase.winThat = undefined;
    PPurchase.dgType = undefined;
};
PPurchase.dg = function () {
    // $.ajax({
    //     type: "POST",
    //     url: "/wRelativeUnit/supplier/listNotPage",
    //     dataType: "json",
    //     success: function (data) {
    //         PPurchase.supplierArr = data;
    //     }
    // });

    $.ajax({
        type: "POST",
        url: "/sysDict/materiel_MU",
        dataType: "json",
        success: function (data) {
            PPurchase.unitArr = data;
        }
    });
    $.ajax({
        type: "POST",
        url: "/wWearhouse/list",
        dataType: "json",
        success: function (data) {
            PPurchase.repositoryArr = data;
        }
    });

    PPurchase.dtable = $('#pPurchase_table');
    PPurchase.dtable.datagrid({
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        toolbar: [
            {
                text: '增加（Insert）', iconCls: 'icon-add', handler: function () {
                    PPurchase.add();
                }
            },
            {
                text: '删除（Del）', iconCls: 'icon-remove', handler: function () {
                    PPurchase.remove();
                }
            },
        ],
        columns: [[
            {field: 'wearhouseId', hidden: true},//仓库
            {field: 'positionId', hidden: true},//库位
            {field: 'skusId', checkbox: true},//规格id
            {field: 'goodsName', title: '商品名称', width: 150},
            // {field: '11', title: '', width: 30,formatter:function () {
            //    return '<button onmouseover="this.style.backgroundColor=\'#E39300\'" onmouseout="this.style.backgroundColor=\'#0099FF\'" style="width:30px;background-color: #0099FF;border-radius:2px;color:white;border: 0px;" onclick="PPurchase.add()">🔍</button>'
            // }},
            {field: 'goodsId', title: '商品ID', width: 80, hidden: true},
            {field: 'skus', title: '规格', width: 200},
            {
                field: 'count',
                title: '<span style="color:blue">采购数量</span><span style="color:red">*</span>',
                width: 50,
                editor: {type: 'numberbox', options: {required: true, min: 1, precision: 0}}
            },
            {
                field: 'amountActual',
                title: '<span style="color:blue">实际进价</span><span style="color:red">*</span>',
                width: 50,
                editor: {type: 'numberbox', options: {required: true, min: 0, precision: 2}}
            },
            {
                field: 'amount', title: '参考进价', width: 50, formatter: function (value, row, index) {
                    return Number(value).toFixed(2);
                }
            },
            {
                field: 'shouldPay', title: '应付金额', width: 50, formatter: function (value, row, index) {
                return Number(value).toFixed(2);
            }
            },

            // {
            //     field: 'unit', title: '单位', width: 50, formatter: function (value, row, index) {
            //         for (var i = 0; i < PPurchase.unitArr.length; i++) {
            //             if (value == PPurchase.unitArr[i].id) {
            //                 return PPurchase.unitArr[i].text;
            //             }
            //         }
            //         return value;
            //     }
            // },
            // {
            //     field: 'ralativeId',
            //     title: '<span style="color:blue">供应商</span><span style="color:red">*</span>',
            //     width: 100,
            //     editor: {
            //         type: 'combobox', options: {
            //             required: true,
            //             editable: false,
            //             valueField: 'id',
            //             textField: 'name',
            //             url: "/wRelativeUnit/supplier/list"
            //         }
            //     },
            //     formatter: function (value, row, index) {
            //         for (var i = 0; i < PPurchase.supplierArr.length; i++) {
            //             if (value == PPurchase.supplierArr[i].id) {
            //                 return PPurchase.supplierArr[i].name;
            //             }
            //         }
            //         return value;
            //     }
            // },
            {
                field: 'repositoryId',
                title: '<span style="color:blue">仓库</span><span style="color:red">*</span>',
                width: 100,
                editor: {
                    type: 'combobox', options: {
                        required: true,
                        editable: false,
                        method:'post',
                        valueField: 'id',
                        textField: 'name',
                        url: "/wWearhouse/list"
                    }
                },
                formatter: function (value, row, index) {
                    for (var i = 0; i < PPurchase.repositoryArr.length; i++) {
                        if (value == PPurchase.repositoryArr[i].id) {
                            return PPurchase.repositoryArr[i].name;
                        }
                    }
                    return value;
                }
            },
            // {
            //     field: 'house',
            //     title: '<span style="color:blue">仓库/库位</span><span style="color:red">*</span>',
            //     width: 100,
            //     editor: {type: 'house'},
            //     formatter: function (value, row, index) {
            //         if (PPurchase.isEmpty(value)) {
            //             return "";
            //         }
            //         var arr = value.split("_");
            //         return "<a style='color:purple'>" + arr[1] + "：" + arr[3] + "</a>";
            //     }
            // },
            // {field: 'batchCode', title: '<span style="color:blue">批号</span>', width: 80, editor: {type: 'text'}},
            {field: 'code', title: '商品编号', width: 80},
            {field: 'OECode', title: 'OE编号', width: 80},
            {
                field: 'car', title: '适用车型', width: 150, hidden:false, formatter: function (value, row, index) {
                    return PPurchase.formatDetail(value);
                }
            },



            // {
            //     field: 'payStatus',
            //     title: '<span style="color:blue">是否挂账</span><span style="color:red">*</span>',
            //     width: 50,
            //     editor: {
            //         type: 'combobox', options: {
            //             required: true,
            //             editable: false,
            //             valueField: 'label',
            //             textField: 'value',
            //             data: [{
            //                 label: '0',
            //                 value: '是'
            //             }, {
            //                 label: '1',
            //                 value: '否'
            //             }]
            //         }
            //     },
            //     formatter: function (value, row, index) {
            //         return value == 0 ? "是" : "否";
            //     }
            // },
            // {
            //     field: 'amountAlready', title: '已付金额', width: 50, formatter: function (value, row, index) {
            //         return Number(value).toFixed(2);
            //     }
            // },
            // {
            //     field: 'remark',
            //     title: '<span style="color:blue">备注</span>',
            //     width: 80,
            //     editor: {type: 'text', options: {required: false}}
            // },
        ]],
        onClickCell: function (index, field) {
            if (PPurchase.editIndex != index) {
                if (PPurchase.editIndex > -1) {
                    PPurchase.dtable.datagrid('endEdit', PPurchase.editIndex);
                }
                PPurchase.editIndex = index;
            }

            if (field == "ralativeId" || field == "batchCode" || field == "amountActual" || field == "count" || field == "payStatus" || field == "remark") {
                PPurchase.dtable.datagrid('beginEdit', index);
            }
        },
        onEndEdit: function (index, row, changes) {
            if (changes) {


                PPurchase.dtable.datagrid('updateRow', {
                    index: index,
                    row: {
                        shouldPay: Number(row.amountActual) * Number(row.count),
                        amountAlready: row.payStatus == "1" ? Number(row.amountActual) * Number(row.count) : 0
                    }
                });
                var rows = PPurchase.dtable.datagrid("getRows");
                var totalMoney = 0;
                for(var i = 0; i< rows.length; i++) {
                    totalMoney = (totalMoney + rows[i].shouldPay).toFixed(2);
                }
                $('#totalMoney').val(totalMoney);
                $('#realPay').val(totalMoney);
                //修改的是“是否挂账”，同步到相同供应商下
                // if (changes.payStatus != undefined && !PPurchase.isEmpty(row.ralativeId)) {
                //     var rows = PPurchase.dtable.datagrid("getRows");
                //     for (var i = 0; i < rows.length; i++) {
                //         if (i != index && rows[i].ralativeId == row.ralativeId) {
                //             PPurchase.dtable.datagrid('updateRow', {
                //                 index: i,
                //                 row: {
                //                     payStatus: changes.payStatus,
                //                     shouldPay: Number(rows[i].amountActual) * Number(rows[i].count),
                //                     amountAlready: changes.payStatus == "1" ? Number(rows[i].amountActual) * Number(rows[i].count) : 0
                //                 }
                //             });
                //         }
                //     }
                // }

                //修改的是供应商
                // if (changes.ralativeId != undefined) {
                //     //先找到修改后供应商的挂账状态，若跟当前修改行状态不一致，则修改当前行
                //     var rows = PPurchase.dtable.datagrid("getRows");
                //     for (var i = 0; i < rows.length; i++) {
                //         if (i != index && rows[i].ralativeId == row.ralativeId && rows[i].payStatus != row.payStatus) {
                //             PPurchase.dtable.datagrid('updateRow', {
                //                 index: index,
                //                 row: {
                //                     payStatus: rows[i].payStatus,
                //                     shouldPay: Number(row.amountActual) * Number(row.count),
                //                     amountAlready: rows[i].payStatus == "1" ? Number(row.amountActual) * Number(row.count) : 0
                //                 }
                //             });
                //             break;
                //         }
                //     }
                // }

                //修改批号
                // if (changes.batchCode != undefined && !PPurchase.isEmpty(changes.batchCode)) {
                //     //当前页面中批号不能重复
                //     var rows = PPurchase.dtable.datagrid("getRows");
                //     var isOk = true;
                //     for (var i = 0; i < rows.length; i++) {
                //         if (i != index && row.batchCode != "" && rows[i].batchCode == row.batchCode) {
                //             PPurchase.canSave = false;
                //             $yd.alert("批号不能重复", function () {
                //                 PPurchase.canSave = true;
                //                 PPurchase.dtable.datagrid('updateRow', {
                //                     index: index,
                //                     row: {
                //                         batchCode: ""
                //                     }
                //                 });
                //             });
                //             isOk = false;
                //             break;
                //         }
                //     }
                //
                //     //数据库中不能重复
                //     if (isOk) {
                //         $yd.post("/inRepositoryDetail/getBatchCodeIsExsit", {batchCode: changes.batchCode}, function (data) {
                //             if (data == 1) {
                //                 PPurchase.canSave = false;
                //                 $yd.alert("已存在相同批号", function () {
                //                     PPurchase.canSave = true;
                //                     PPurchase.dtable.datagrid('updateRow', {
                //                         index: index,
                //                         row: {
                //                             batchCode: ""
                //                         }
                //                     });
                //                 });
                //             }
                //         });
                //     }
                // }
            }
        }
    });

    PPurchase.dtable.datagrid('enableCellEditing');
};

PPurchase.formatDetail = function (value) {
    if ($yd.isEmpty(value)) {
        return "";
    }
    var result = "";
    var first = "";
    var arr = value.split(",");
    if (arr.length == 1) {
        return "<a style='color:purple' title='" + value + "'>" + value + "</a>";
    }
    for (var i = 0; i < arr.length; i++) {
        result += arr[i] + "\n";
        if (i == 0) {
            first = result;
        }
    }
    var html = "<a style='color:purple' title='" + result + "'>" + first + "..." + "</a>";

    return html;
};

PPurchase.refresh = function () {
    window.location.reload();
};

PPurchase.add = function () {
    var href = "/mMateriel/searchDg";
    var $dg = $yd.win.create('商品', href);
    $dg.width = "1050px;";
    $dg.height = "400px;";
    PPurchase.isDg = 1;
    $dg.open(function (that, $win) {
            PPurchase.winThat = that;
            PPurchase.dgType = "goods";
        }, function (that, $win) {
            PPurchase.saveDgGoods();
        }, function () {
            PPurchase.isDg = 0;
            PPurchase.winThat = undefined;
            PPurchase.dgType = undefined;
            document.onkeydown = PPurchase.keyDown;
        }
    );
};
PPurchase.isExist = function(rows, skusId) {
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].skusId == skusId) {
            return true;
        }
    }
    return false;
};
PPurchase.saveDgGoods = function() {
    document.onkeydown = PPurchase.keyDown;

    var data = Goods.getChecked();
    if (data.length == 0) {
        PPurchase.winThat.close();
        PPurchase.isDg = 0;
        PPurchase.winThat = undefined;
        PPurchase.dgType = undefined;
        return;
    }

    var rows = PPurchase.dtable.datagrid("getData").rows;
    for (var i = 0; i < data.length; i++) {
        if (!PPurchase.isExist(rows, data[i].skuId)) {
            PPurchase.dtable.datagrid('appendRow', {
                skusId: data[i].skuId,
                goodsName: data[i].goodsName,
                goodsId: data[i].goodsId,
                skus: data[i].skusName,
                code: data[i].code,
                unit: data[i].unit,
                ralativeId: data[i].ralativeId,
                payStatus: "0",
                amount: data[i].buyPrice,
                amountActual: data[i].buyPrice,
                count: 1,
                shouldPay: Number(data[i].buyPrice) * Number(1),
                amountAlready: 0,
                wearhouseId: data[i].wearhouseId,
                repositoryId: data[i].wearhouseId,
                positionId: data[i].positionId,
                house: data[i].wearhouseId + "_" + data[i].wearhouseName + "_" + data[i].positionId + "_" + data[i].positionName,
                car: data[i].car,
                OECode : data[i].partsCode
            }).datagrid('clearSelections');
            var totalMoney = $('#totalMoney').val();
            totalMoney = (Number(totalMoney) + Number(data[i].buyPrice) * Number(1)).toFixed(2);
            $('#totalMoney').val(totalMoney);
            $('#realPay').val(totalMoney);
        }
    }
    PPurchase.winThat.close();
    PPurchase.isDg = 0;
    PPurchase.winThat = undefined;
    PPurchase.dgType = undefined;

    var list = $(":checkbox");
    var tmp = 0;
    for(var i=1; i<list.length; i++) {
        var td = $(list[i]).closest("td");
        if(td.hasClass("datagrid-row-selected")) {
            tmp = i;
        }
    }
    if(tmp == 0) {
        $(list[1]).closest("td").trigger("click");
    }
};

Array.prototype.contains = function (needle) {
    for (var i in this) {
        if (this[i] == needle) return true;
    }
    return false;
};

//删除
PPurchase.remove = function () {
    var sels = PPurchase.dtable.datagrid('getChecked');
    if (sels.length == 0) {
        $yd.alert('请选中记录');
        return;
    }
    var ids = [];
    $.each(sels, function (i, n) {
        ids.push(n['skusId']);
    });

    $.each(ids, function (i, n) {
        var rows = PPurchase.dtable.datagrid('getRows');
        for (var ii = 0; ii < rows.length; ii++) {
            if (rows[ii].skusId == n) {
                PPurchase.dtable.datagrid('deleteRow', ii);
                break;
            }
        }
    });

    var tds = $(".datagrid-row-selected");
    if(tds.length==0) {
        var checks = $(":checkbox");
        if(checks.length>1) {
            $(checks[1]).closest("td").trigger("click");
        }
    }
};

PPurchase.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
};
PPurchase.save0 = function () {
    PPurchase.save(0);
};
PPurchase.save1 = function () {
    PPurchase.save(1);
};
PPurchase.save = function (type) {
    if(PPurchase.isEmpty($('#relativeId').val())){
        $yd.alert("请选择供应商");
        return false;
    }

    //结束编辑状态
    if (PPurchase.editIndex != undefined && PPurchase.editIndex != -1) {
        PPurchase.dtable.datagrid('endEdit', PPurchase.editIndex);
    }

    if (PPurchase.canSave == false) {
        return;
    }

    $('#myForm').form('submit', {
        url: PPurchase.uEdit,
        onSubmit: function () {
            var isValid = $('#myForm').form('validate');//只能校验处于编辑状态的栏位
            if (!isValid) {
                return isValid;
            }

            //校验数据
            var rows = PPurchase.dtable.datagrid("getRows");
            if (rows.length == 0) {
                $yd.alert("请添加商品");
                return false;
            }

            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                // if (PPurchase.isEmpty(row.ralativeId)) {
                //     $yd.alert("第" + (i + 1) + "行：供应商不能为空");
                //     return false;
                // }

                // if (row.amount !=0 &&PPurchase.isEmpty(row.amount)) {
                //     $yd.alert("第" + (i + 1) + "行：参考进价不能为空");
                //     return false;
                // }
                // if (row.amountActual != 0 &&PPurchase.isEmpty(row.amountActual)) {
                //     $yd.alert("第" + (i + 1) + "行：实际进价不能为空");
                //     return false;
                // }
                if (PPurchase.isEmpty(row.count)) {
                    $yd.alert("第" + (i + 1) + "行：数量不能为空");
                    return false;
                }

                if (PPurchase.isEmpty(row.repositoryId)) {
                    $yd.alert("第" + (i + 1) + "行：仓库不能为空");
                    return false;
                }
            }

            //封装数据
            $("#type").val(type);
            $("#goods").val(JSON.stringify(rows));
            return isValid;
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.code == 0) {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            }
        }
    });
};

// 处理按钮
PPurchase.btn = function () {
    var sb = new $yd.SearchBtn($(PPurchase.obtn));
    sb.create('repeat red', '重置（Shift+R）', PPurchase.refresh);
    sb.create('save green', '生单入库（Shift+S）', PPurchase.save1);
    sb.create('save green', '生单（Shift+A）', PPurchase.save0);
};
PPurchase.keyDown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    // console.log("add.js")
    if(e.keyCode==9) {
        if (e.preventDefault) {
            e.preventDefault();
        }
        else {
            e.returnValue = false;
        }
    }
};
PPurchase.keyUp = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (!e) {
        return;
    }
    if (e.keyCode == 13 && PPurchase.dgType == "goods") {
        PPurchase.saveDgGoods();
    } else if (e.keyCode == 13 && PPurchase.dgType == "house") {
        PPurchase.saveDgHouse();
    }
    if(PPurchase.isDg != 0 && e.keyCode==27 && PPurchase.winThat) {//ESC
        PPurchase.winThat.close();
    }
    if(PPurchase.isDg == 0) {
        if(e.keyCode==45) {//insert
            PPurchase.add();
        }
        if(e.keyCode==46) {//del
            PPurchase.remove();
        }
        if(e.keyCode==32) {//space
            var tds = $(".datagrid-row-selected");
            if(tds.length>0) {
                var check = $(tds).find(":checkbox")[0];
                $(check).trigger("click");
            }
        }
        if (e.shiftKey && e.keyCode == 83){
            PPurchase.save(1);//生单入库：Shfit + A
        }
        if (e.shiftKey && e.keyCode == 65){
            PPurchase.save(0);//生单: Shift + S
        }
        if (e.shiftKey && e.keyCode == 82){
            PPurchase.refresh();
        }
    }
};
PPurchase.init = function() {
    //默认值
    $("input[name='purchaseType']").combobox({
        url: "/sysDict/purchase_type",
        panelHeight: 'auto',
        required: true,
        valueField: 'id',
        textField: 'text',
        editable: false,
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].value);
        }
    });

    $("input[name='ptime']").datebox({
        required: true,
        editable: false,
        value: new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate()
    });

    //鼠标点击页面任何地方，表格编辑结束编辑状态
    document.onclick = PPurchase.mouseClick;

    //快捷键
    document.onkeydown = PPurchase.keyDown;
    document.onkeyup = PPurchase.keyUp;

    setTimeout("$('#pPurchase_table').focus()", 500);
};
PPurchase.mouseClick = function(e) {
    e = window.event || e; // 兼容IE7
    var obj = $(e.srcElement || e.target);

    if (PPurchase.isDg == 0 && !$(obj).hasClass("datagrid-cell") && !$(obj).hasClass("datagrid-row-over")) {
        if (PPurchase.editIndex != -1) {
            PPurchase.dtable.datagrid('endEdit', PPurchase.editIndex);
            PPurchase.editIndex = -1;
        }
    }
};
$(function () {
    PPurchase.obtn = '#pPurchase_btn';

    PPurchase.dg(); // 数据表格
    PPurchase.btn(); // 初始化按钮
    PPurchase.init(); // 数据表格

    $("input[name='payStatus']").combobox({
        url: "/sysDict/purchase_next_status",
        panelHeight: 'auto',
        valueField: 'id',
        textField: 'text',
        editable: false,
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].id);
        },
    });

    $("input[name='relativeId']").combobox({
        url: "/wRelativeUnit/supplier/list",
        panelHeight: 'auto',
        valueField: 'id',
        textField: 'name',
        editable: false,
    });
});